package cn.com.w.bootdemo.util;

import java.io.IOException;
import java.net.URL;
import java.util.*;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;

/**
 * 自定义获取class:config/config.properties文件工具类
 */
@Component
public class ConfigrationCustomConfig {

    private static final Logger LOG = LoggerFactory.getLogger(ConfigrationCustomConfig.class);
    private static Properties properties = new Properties();
    private static final String path = "config/config.properties";

    /**
     * 获取指定key的value，无默认值
     * @param key
     * @return
     */
    public static String getConfig(String key) {
        return getConfig(key, (String)null);
    }

    /**
     * 获取指定key的value，有默认值
     * @param key
     * @param defaultValue
     * @return
     */
    public static String getConfig(String key, String defaultValue) {
        return properties.getProperty(key, defaultValue);
    }

    /**
     * 获取全部key-value
     * @return
     */
    public static Map<String, String> getConfigurations() {
        Map map = new HashMap();
        map.putAll(properties);
        return map;
    }

    /**
     * 加载指定配置文件
     */
    static {
        try {
            Enumeration<URL> configs = ConfigrationCustomConfig.class.getClassLoader().getResources(path);
            properties = new Properties();
            ArrayList classProperties = new ArrayList();

            while(true) {
                Properties p;
                while(configs.hasMoreElements()) {
                    URL config = (URL)configs.nextElement();
                    if (LOG.isDebugEnabled()) {
                        LOG.debug("load config: " + config.getFile());
                    }

                    p = new Properties();
                    p.load(config.openStream());
                    if (config.getPath().contains("classes/") && !config.getPath().contains(".jar!")) {
                        classProperties.add(p);
                    } else {
                        properties.putAll(p);
                    }
                }

                if (!ObjectUtils.isEmpty(classProperties)) {
                    Iterator i$ = classProperties.iterator();

                    while(i$.hasNext()) {
                        p = (Properties)i$.next();
                        properties.putAll(p);
                    }
                }
                break;
            }
        } catch (IOException var4) {
            LOG.error("", var4);
        }

    }


}
